package com.atstudy.controller;

import com.atstudy.entites.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/2/15 11:12
 * @copyright: 博为峰
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    //    @RequestMapping(value = "/getAccountList", method = RequestMethod.GET)
    @GetMapping(value = "/getAccountList")
    public String getAccountList(ModelMap map, Model model) {
        System.out.println("AccountController = getAccountList 1");
        Account account = new Account(1, "zhangsan", 1000);
        map.addAttribute("account", account);
        int i = 1 / 0;
        return "account_list";
    }

    @RequestMapping(value = "/getAccountByName")
    public ModelAndView getAccountByName(String name) {
        System.out.println("name = " + name);
        ModelAndView modelAndView = new ModelAndView();
        Account account = new Account(1, "zhangsan", 1000);
        modelAndView.addObject("account", account);
        modelAndView.setViewName("account_list");
        return modelAndView;
    }

    @PostMapping(value = "/addAccount")
    public String addAccount(@Validated Account account, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.stream().forEach(e-> System.out.println(e.getDefaultMessage()));
        }
        System.out.println("account = " + account);
        return "account_list";
    }

    @RequestMapping(value = "/getAccountByIdName/{id}/{name}")
    public String getAccountByIdName(@PathVariable("id") int id, @PathVariable("name") String name) {
        System.out.println("id = " + id);
        System.out.println("name = " + name);
        return "redirect:account_list";
    }

    @RequestMapping(value = "/testAnno")
    public void testAnno(@RequestHeader("User-Agent") String userAgent,
                         @CookieValue("JSESSIONID") String cookie,
                         HttpServletRequest request,
                         HttpServletResponse response,
                         HttpSession session) throws IOException {
        response.sendRedirect(request.getContextPath() + "/account_list.jsp");
    }
}
